package cur.nature.starter.common.config;

import cur.nature.framework.core.log.LOG;
import cur.nature.framework.core.util.IdUtil;
import cur.nature.framework.core.util.SnowflakeIdUtil;
import jakarta.annotation.PostConstruct;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.net.Inet4Address;
import java.net.UnknownHostException;

@Configuration
public class IdConfig {

    @Value("${server.port}")
    private int port;

    @PostConstruct
    public void init() {
        final Long workerId = getWorkId();
        LOG.info("workerId:{}", workerId);
        // 初始化snowflake, 有序
        SnowflakeIdUtil idGenerator = new SnowflakeIdUtil(workerId);
        SnowflakeIdUtil.setIdWorker(idGenerator);
        // 初始化uuid, 无序
        IdUtil idUtil = new IdUtil(workerId);
        IdUtil.setWorkId(idUtil);
    }

    // 取0-255位机器码, 通过 ip 加 端口 计算出来, 也可以通过数据库配置
    private Long getWorkId(){
        try {
            String hostAddress = Inet4Address.getLocalHost().getHostAddress() + port;
            int[] ints = StringUtils.toCodePoints(hostAddress);
            int sums = 0;
            for(int b : ints){
                sums += b;
            }
            return (long)(sums % 256);
        } catch (UnknownHostException e) {
            // 如果获取失败，则使用随机数备用
            return RandomUtils.nextLong(0,255);
        }
    }
}
